/**
 * 点菜
 */
;(function ($) {
	//积分卡模态入口
	$.fn.specialDishes=function(options){
    	//创建对象
		var app = new special(this, options);
		//构造模态
		app.html(); 
	}
	
	//构造函数
    var special = function(ele, opt) {   	
    	//选择器对象    	
        this.$element=ele;   
        //默认参数
        this.defaults = {
        	data:null,
        	doPopup:true,//是否循环弹出必选项
        	enabled:"",//可修改项
			popup:"",//必选项
	    	pupupIndex:0,//必输项序号
	    	popupCopy:new Array(),//必输项
			fwy : "",
    		returnBack:function(){},//返回回调函数
    		dataBack:function(){},//完成回调函数
        },        
        //初始化参数
        this.options = $.extend({}, this.defaults, opt);
    }
    
    //属性方法
    special.prototype = {
        //数据
    	defaulValue:null,
    	//构造html
    	html:function(){
    		var $t=this;
    		var $opt=$t.options;
    		
    		$t.$element.addClass("modal").attr("tabindex","-2").attr("data-backdrop","static")//.css("left","25%")  
	    		html='<div class="modal-dialog pay_general coupon_search score_search" style="width:500px;">'+ 
						'<div class="modal-content">'+      
				  			'<div class="modal-header no-padding">'+
								'<div class="table-header widget-header-large " style="text-align:center; font-size:20px">'+  
									'<span>'+$.i18n.propJsp("菜品编辑")+'</span>'+       
								'</div>'+
							'</div>'+
							'<div class="modal-body modal-coupon" style="height:530px">'+     
								'<div class="mykb-box" id="specialDishesKeyBoard"></div>'+
								'<form id="specialSave">'+
									'<div class="input-group">'+
										'<span class="input-group-addon">'+
											$.i18n.propJsp("编号:")+
										'</span>'+
										'<input type="text" class="form-control search-query" placeholder="" name="bh" readonly>'+ 
									'</div>'+
									'<div class="input-group">'+
										'<span class="input-group-addon">'+
											$.i18n.propJsp("金额:")+
										'</span>'+
										'<input type="text" class="form-control search-query test" placeholder="" name="je" readonly>'+
									'</div>'+
									'<div class="input-group">'+
										'<span class="input-group-addon">'+
											$.i18n.propJsp("名称:")+
										'</span>'+
										'<input type="text" class="form-control search-query" placeholder="" name="mc" readonly>'+
									'</div>'+
									'<div class="input-group">'+ 
										'<span class="input-group-addon">'+ 
											$.i18n.propJsp("数量:")+
										'</span>'+ 
										'<input data-title="数量" value="1.00" type="text" class="form-control search-query test inputEntry" placeholder="" name="sl" />'+// onfocus="this.blur()"
										'<span class="input-group-btn">'+
											'<button type="button" data-name="sl" class="btn btn-primary btn-sm" id="sl_help">'+
    											'<span class="ace-icon fa fa-keyboard-o icon-on-right bigger-110"></span>'+
											'</button>'+
										'</span>'+
									'</div>'+
									'<div class="input-group">'+ 
										'<span class="input-group-addon">'+
											$.i18n.propJsp("单位:")+ 
										'</span>'+
										'<input type="text" class="form-control search-query" placeholder="" name="dw" readonly>'+
										'<span class="input-group-btn">'+
											'<button type="button" class="btn btn-primary btn-sm disabled" id="dw_help">'+  
												'<span class="ace-icon fa fa-search icon-on-right bigger-110"></span>'+$.i18n.propJsp("选择")+
											'</button>'+
										'</span>'+
									'</div>'+
									'<div class="input-group">'+ 
										'<span class="input-group-addon">'+
											$.i18n.propJsp("规格:")+
										'</span>'+
										'<input type="text" class="form-control search-query" placeholder="" name="dw2" readonly>'+
										'<span class="input-group-btn">'+
											'<button type="button" class="btn btn-primary btn-sm disabled" id="dw2_help">'+  
												'<span class="ace-icon fa fa-search icon-on-right bigger-110"></span>'+$.i18n.propJsp("选择")+
											'</button>'+
										'</span>'+
									'</div>'+
									'<div class="input-group">'+ 
										'<span class="input-group-addon">'+
											$.i18n.propJsp("单价:")+
										'</span>'+
										'<input data-title="单价" type="text" class="form-control test search-query" placeholder="" name="dj" readonly/>'+// onfocus="this.blur()"
										'<span class="input-group-btn">'+
											'<button type="button" data-name="dj" class="btn btn-primary btn-sm disabled" id="dj_help">'+
												'<span class="ace-icon fa fa-keyboard-o icon-on-right bigger-110"></span>'+
											'</button>'+
										'</span>'+
									'</div>'+
									'<div class="input-group">'+ 
										'<span class="input-group-addon">'+
											$.i18n.propJsp("服务员:")+ 
										'</span>'+
										'<input type="text" class="form-control search-query" placeholder="" name="jgbh" readonly>'+
										'<span class="input-group-btn">'+
											'<button type="button" class="btn btn-primary btn-sm disabled" id="jgbh_help">'+   
												'<span class="ace-icon fa fa-search icon-on-right bigger-110"></span>'+$.i18n.propJsp("选择")+
											'</button>'+
										'</span>'+
									'</div>'+
									'<div class="input-group">'+ 
										'<span class="input-group-addon">'+ 
											$.i18n.propJsp("做法:")+
										'</span>'+
										'<input type="text" class="form-control search-query inputEntry" placeholder="" name="zf" />'+ //readonly   
										'<span class="input-group-btn">'+
											'<button type="button" class="btn btn-primary btn-sm disabled" id="zf_help">'+ //  
												'<span class="ace-icon fa fa-edit icon-on-right bigger-110"></span>'+ $.i18n.propJsp("选择")+
											'</button>'+
										'</span>'+
									'</div>'+
								'</form>'+
							'</div>'+	
							'<div class="modal-footer">'+
								'<button id="btnSure" class="btn btn-info btn-lg btn-round">'+  
									'<i class="ace-icon fa fa-check"></i>'+$.i18n.propJsp("确定")+
								'</button>'+
								'<button id="btnCancel" class="btn btn-default btn-lg btn-round">'+  
									'<i class="ace-icon fa fa-undo"></i>'+$.i18n.propJsp("返回")+'</button>'+ 
								'</button>'+
							'</div>'+		
		  				'</div>'+
		  			'</div>'+		
				'</div>'+
			'</div>';
    		
    		//添加到容器
    		$t.$element.html(html);
    		
    		//初始化模态
    		$t.initValue();
    	},
    	//初始化
    	initValue:function(){
    		var $t=this;
    		var $opt=$t.options;
    		var el=$t.$element;
    		$t.defaulValue=$opt.data;
    		
    		//赋值
    		for(var item in $t.defaulValue){
				el.find("input[name='"+item+"']").val($t.defaulValue[item]);
				el.find("input[name='"+item+"']").attr("data-value",$t.defaulValue[item]);
    		}
    		if(!$t.defaulValue.hasOwnProperty("sl"))
    			$t.defaulValue["sl"]="1.00"; 
    		//数量单独处理->可为0入账情况下初始化为0
    		if($t.defaulValue.hasOwnProperty("hcdm")){ 
    			//第二位为1表示可数量为0入账
    			if($t.defaulValue.hcdm=="01"||$t.defaulValue.hcdm=="11"){ 
    				el.find("input[name='sl']").val("0.00");
    				//重新计算金额
    				$t.CalculatedAmount();
    			}
    		}
    		
    		//可改
    		$($opt.enabled.split(",")).each(function(k,v){ 
    			if(v!=""){
    				el.find("input[name='"+v+"']").prop("readonly",false).addClass("inputEntry");
    				el.find("#"+v+"_help").removeClass("disabled");
    			}	  
    		});
    		
    		//必选
    		$($opt.popup.split(",")).each(function(k,v){  
    			if(v!="")
    				el.find("#"+v+"_help").removeClass("disabled");
    			//金额单独处理
    			if(v=="dj")
    				el.find("input[name='dj']").prop("readonly",false); 
    			//做法可自行输入
    			if(v=="zf")
    				el.find("input[name='zf']").prop("readonly",false);
    		});
    		
    		//服务员
    		el.find("#jgbh_help").bind("click",function(e){
    			el.css("opacity",0); 
    			$t.selFwy(function(data){
    				$t.defaulValue.jgbh=data;
    				el.find("input[name='jgbh']").val(data);
    				//执行下一个必选项
    				if(!e.hasOwnProperty('originalEvent'))
    					$t.doPopup();
    			});   
    		});
    		
    		//多单位
    		el.find("#dw2_help").bind("click",function(e){
    			el.css("opacity",0);
    			$t.selDw2(function(data){
//    				alert(data)
    				el.find("input[name='dw2']").val(data.zf);
    				el.find("input[name='zf']").val(data.zf);
    				el.find("input[name='sl']").val($t.checkTwoPoint(data.sl)); 
    				//执行下一个必选项
    				if(!e.hasOwnProperty('originalEvent'))
    					$t.doPopup();
    			});
    		});
    		
    		//单位明细
    		el.find("#dw_help").bind("click",function(e){
    			el.css("opacity",0);
    			$t.selManyUnit(function(data){
    				//单位
    				el.find("input[name='dw']").val(data.dw); 
    				//单价
    				el.find("input[name='dj']").val($t.checkTwoPoint(data.dj));
    				//重新计算金额
    				$t.CalculatedAmount(); 
    				//执行下一个必选项
    				if(!e.hasOwnProperty('originalEvent'))
    					$t.doPopup();
    			}); 
    		});
    		
    		//做法
    		el.find("#zf_help").bind("click",function(e){
    			el.css("opacity",0);
    			$t.selHcdm(function(data){
    				el.find("input[name='zf']").val(data);
    				//执行下一个必选项
    				if(!e.hasOwnProperty('originalEvent'))
    					$t.doPopup();
    			});
    		});
    		
    		//初始化金额
    		$t.CalculatedAmount(); 
    		
    		//绑定事件
    		$t.bindEvent();
    		
    		//循环调用必选项
    		if($opt.doPopup){
    			$($opt.popup.split(",")).each(function(k,v){  
    				if(el.find("#"+$opt.popup.split(",")[k]+"_help").length>0){ 
    					$opt.popupCopy.push(v);
    				}	
    			}); 
    			$("#"+$opt.popupCopy[$opt.pupupIndex]+"_help").trigger("click");
    		}
    		
    		//数量、单位可修改
    		el.find(".inputEntry").click(function(){
    			var name = this.name
    			if(name!="zf"){
    				$(this).select();
    			}
    		})
    		
    		el.find(".inputEntry").keyup(function(){
    			var name = $(this).attr("name");
    			var $dom=el.find("input[name="+name+"]");
    			var value = $(this).val();
    			if($(this).hasClass("test")){
    				value = value.replace(/[^\-^\d^\.]+/g,"");
    				$(this).val(value);
    				value = $t.checkTwoPoint(value);
    			}
    			data=value;
    			if(name=="dw2"){
    				var dw2 = el.find("input[name=dw2]").data("value");
    				if(data.indexOf(dw2)>-1){
    					data = data.replace(dw2,"").replace(/[^\-^\d^\.]+/g,"")
    					if(data){
    						data = $t.checkTwoPoint(data)+dw2
    						$t.defaulValue.zf = data;
    					}else{
    						$t.defaulValue.zf = "";
    					}
    				}else{
    					if(data){
    						$t.defaulValue.zf = $t.checkTwoPoint(data)+dw2;
    					}else{
    						$t.defaulValue.zf = "";
    					}
    					
    				}
    			}else{
    				$t.defaulValue[name]=data;
    			}
    			//重新计算金额
				$t.CalculatedAmount();
    		})
    	},
    	//服务员插件
    	selFwy:function(dataBack){
    		var $t=this;
    		var $opt=$t.options;
    		var el=$t.$element;
    		
//			$.ajaxSetup({ async: false, cache: false });
//            $.getScript($t.getContextPath()+"/static/pos/js/posorder/jquery.modal.sel_fwy2.js");
//            $.ajaxSetup({ async: true }); 
//            
//    		var uuid=$t.uuid();
//    		el.parent().append('<div id="'+uuid+'" class="modal" data-backdrop="static"></div>');  
// 
//    		$("#"+uuid).modal("show");
//    		$("#"+uuid).sel_fwy({
//    		    multi:false,
//    		    unUnames : [],
//    		    dataBack : function(data){
//    		    	el.css("opacity",1);
//    		    	dataBack(data[0].uname);
//    		    	$t.destroyModal(uuid);
//        		},
//        		closeBack : function(){
//        			el.css("opacity",1);
//        			$t.destroyModal(uuid);
//        		},
//    		});


			$.ajaxSetup({ async: false, cache: false });
	        $.getScript("js/cashier_mana/jquery.modal.pos_sel_fwy.js");
	        $.ajaxSetup({ async: true });
            
    		var uuid=$t.uuid();
    		el.parent().append('<div id="'+uuid+'" class="modal" data-backdrop="static"></div>');  
 
    		$("#"+uuid).modal("show");
    		$("#"+uuid).pos_sel_fwy({
    		    multi:false,
    		    unUnames : [],
				fwy : $opt.fwy,
    		    dataBack : function(data){
    		    	el.css("opacity",1);
    		    	dataBack(data.uname);
    		    	$t.destroyModal(uuid);
        		},
        		closeBack : function(){
        			el.css("opacity",1);
        			$t.destroyModal(uuid);
        		},
    		});
    		
    	},
    	//多单位
    	selDw2:function(dataBack){
    		var $t=this;
    		var $opt=$t.options;
    		var el=$t.$element;
    		
    		$.ajaxSetup({ async: false, cache: false });
    		$.getScript("js/cashier_mana/jquery.modal.many_unit.js");
            $.ajaxSetup({ async: true });
            el.modal("toggle");
            var uuid=$t.uuid();
    		el.parent().append('<div id="'+uuid+'" class="modal" data-backdrop="static"></div>');
    		var dw2 = el.find("input[name=dw2]:eq(0)").data("value");
    		$("#"+uuid).modal("show");  
    		$("#"+uuid).many_unit({
				ds : $t.defaulValue,
				dw2 : dw2,
				dataBack : function(data){
					el.modal("toggle");
					el.css("opacity",1);
					$t.defaulValue=data;  
					dataBack(data);
    		    	$t.destroyModal(uuid);
				},
				closeBack : function(){
					el.modal("toggle");
					el.css("opacity",1);
        			$t.destroyModal(uuid);
				}
			});
    		
    	},
    	//选择单位明细
    	selManyUnit:function(dataBack){
    		var $t=this;
    		var $opt=$t.options;
    		var el=$t.$element;
    		
    		$.ajaxSetup({ async: false, cache: true});
            $.getScript("js/cashier_mana/jquery.unitmeal.js");
            $.ajaxSetup({ async: true , cache: false});
            
            var uuid=$t.uuid();
    		el.parent().append('<div id="'+uuid+'" class="modal" data-backdrop="static"></div>');
    		
    		$("#"+uuid).modal("show");
    		$("#"+uuid).unitmeal({
				data:$t.defaulValue.manyunit_detail,
	    		dataBack : function(data){
					el.css("opacity",1);
					$t.defaulValue=$.extend({},$t.defaulValue,data);
					dataBack(data);
			    	$t.destroyModal(uuid);
				},
				closeBack : function(){
					el.css("opacity",1);
	    			$t.destroyModal(uuid);
				}
			});
    	},
    	//做法
    	selHcdm:function(dataBack){
    		var $t=this;
    		var $opt=$t.options;
    		var el=$t.$element;
    		
    		$.ajaxSetup({ async: false, cache: true});
            $.getScript("js/cashier_mana/jquery.modal.service_way.js");
            $.ajaxSetup({ async: true , cache: false});
            
            var uuid=$t.uuid();
            el.parent().append('<div id="'+uuid+'" class="modal" data-backdrop="static"></div>'); 
    		
    		$("#"+uuid).modal("show");
    		$("#"+uuid).service_way({  
    			dataBack : function(data){
					el.css("opacity",1);
					$t.defaulValue["zf"]=data;
					dataBack(data);
			    	$t.destroyModal(uuid);
				},
				closeBack : function(){
					el.css("opacity",1);
	    			$t.destroyModal(uuid);
				}
    		});
    	},
    	//计算金额
    	CalculatedAmount:function(){
    		var $t=this;
    		var $opt=$t.options; 
    		var el=$t.$element;
    		
    		try {
    			var dj=el.find("input[name='dj']").val();
        		if(dj=="")
        			dj="0.00"
    			var sl=el.find("input[name='sl']").val(); 
        		if(sl=="")
        			sl="0.00"
        		//金额保留俩位小数且先下取
        		var newJe=$t.getFloorTwo(dj,sl);
    			el.find("input[name='je']").val(newJe); 
        		//更新数据
        		$t.defaulValue["je"]=newJe+''; 
			} catch (e) {
				return;
			}
    	},
    	//绑定事件
    	bindEvent:function(){
    		var $t=this;
    		var $opt=$t.options;
    		var el=$t.$element;
    		
//    		//触摸输入
//    		el.find("input[name='dj'],input[name='sl']").focus(function(){   
//    			if($(this).attr("readonly")=="readonly"||$(this).attr("readonly")==true)  
//    				return;
//    			var $dom=$(this);
//    			var type="price";
//    			if(!$.isFunction($().digitalCalculator)){
//					$.ajaxSetup({ async: false, cache: true });
//					$.getScript($t.getContextPath()+"/static/pos/js/posorder/keyboard/js/jquery.plugin.digitalCalculator.js");
//		            $.ajaxSetup({ async: true , cache: false});
//				}
//				el.find("#specialDishesKeyBoard").digitalCalculator({
//					price:$dom.val(),
//					title:$dom.attr("data-title"),
//					type:type,
//					dataBack:function(data){
//						data=$t.checkTwoPoint(data);
//						$dom.val(data);
//						//更新单价和数量
//						if($dom.attr("name")=="dj")
//							$t.defaulValue["dj"]=$dom.val(); 
//						else if($dom.attr("name")=="sl")
//							$t.defaulValue["sl"]=$dom.val();
//						//重新计算金额
//						$t.CalculatedAmount();
//					}
//				});
//			}); 
    		
    		//触摸输入
    		el.find("#sl_help,#dj_help").focus(function(){   
//    			if($(this).attr("readonly")=="readonly"||$(this).attr("readonly")==true)  
//    				return;
    			var name = $(this).data("name");
    			var $dom=el.find("input[name="+name+"]");
//    			var $dom=$(this);
    			var type="price";
    			if(!$.isFunction($().digitalCalculator)){
					$.ajaxSetup({ async: false, cache: true });
					$.getScript("js/openSpa/jquery.plugin.digitalCalculator.js");
		            $.ajaxSetup({ async: true , cache: false});
				}
				el.find("#specialDishesKeyBoard").digitalCalculator({
					price:$dom.val(),
					title:$dom.attr("data-title"),
					type:type,
					dataBack:function(data){
						data=$t.checkTwoPoint(data);
						$dom.val(data);
						//更新单价和数量
						if(name=="dj")
							$t.defaulValue["dj"]=$dom.val(); 
						else if($dom.attr("name")=="sl")
							$t.defaulValue["sl"]=$dom.val();
						//重新计算金额
						$t.CalculatedAmount();
					}
				});
			}); 
	
    		//取消
    		el.find("#btnCancel").bind("click",function(){
    			el.find("#specialDishesKeyBoard").find(".exit").find("button").trigger("click");   
    			$opt.returnBack();
    		});
    		
    		//确定
    		el.find("#btnSure").bind("click",function(){
    			el.find("#specialDishesKeyBoard").find(".exit").find("button").trigger("click");
				//处理标准宴和套餐
    			if($.inArray("setmenu", $opt.popup.split(","))!=-1){
    				var data=$t.defaulValue;
    				var sort = data.bh; 
    				if(data.hasOwnProperty("tc_detail")){
    					try {
    						data.tc_detail = $.parseJSON(data.tc_detail);
						} catch (e) {
							$opt.dataBack($t.defaulValue);
						}
						if((data.tc_detail).length>0){
	    					$(data.tc_detail).each(function(key,value){
	        					value.suit_xh=sort;
								value.web_xh=key+1;
	        				})
	    				}
    				}
    			}
//    			console.log(JSON.stringify($t.defaulValue));
    			//更新名称
    			$t.defaulValue.mc=el.find("input[name='mc']").val();
    			$t.defaulValue.dw2 = el.find("input[name=dw2]").data("value");
    			$opt.dataBack($t.defaulValue); 
    		});
    	   
    	},
    	//轮流执行必选项
    	doPopup:function(){
    		var $t=this;
    		var $opt=$t.options;
 
    		if($opt.doPopup){
    			if($opt.popupCopy.length-1>=$opt.pupupIndex)
    				$("#"+$opt.popupCopy[++$opt.pupupIndex]+"_help").trigger("click");
    		}	 
    	},
    	//俩位小数校验
    	checkTwoPoint:function(value){
    		var $t=this;
    		var $opt=$t.options;
    		var el=$t.$element;
    		
    		value=value.toString()+".00";
//    		value = value.replace(/[^\d.]/g,""); //清除"数字"和"."以外的字符
//    		value = value.replace(/^\./g,""); //验证第一个字符是数字
    		value = value.replace(/\.{2,}/g,"."); //只保留第一个, 清除多余的
    		value = value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
    		value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3'); //只能输入两个小数
    		
    		return value;
    	},
    	//除法函数
        accDiv:function(arg1,arg2){
        	var t1=0,t2=0,r1,r2; 
        	try{t1=arg1.toString().split(".")[1].length}catch(e){}
        	try{t2=arg2.toString().split(".")[1].length}catch(e){}
        	with(Math){
	        	r1=Number(arg1.toString().replace(".",""))
	        	r2=Number(arg2.toString().replace(".",""))
	        	return (r1/r2)*pow(10,t2-t1); 
        	}
        },
        //乘法函数
        accMul:function(arg1,arg2){ 
        	var m=0,s1=arg1.toString(),s2=arg2.toString();
        	try{m+=s1.split(".")[1].length}catch(e){}
        	try{m+=s2.split(".")[1].length}catch(e){}
        	return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m)
        },
        //唯一标识
        uuid:function(){
        	var oDate = new Date(); 
			var year=oDate.getFullYear();   
			var month=oDate.getMonth()+1;   
			var day=oDate.getDate(); 
			var hour=oDate.getHours(); 
			var min=oDate.getMinutes(); 
			var sen=oDate.getSeconds();
			var x = 32767;     
		    var y = 0;     
		    var rand = parseInt(Math.random() * (x - y + 1) + y);
		    var newId=year+""+month+""+day+""+hour+""+min+""+sen+""+rand;
		    return newId;
        },
        //保留俩位向上取
        getCeilTwo:function(valueF,valueS){ 
        	var $t=this;
        	return $t.accDiv(Math.ceil($t.accMul($t.accMul(valueF,valueS),100)),100);  
        },
        //保留俩位向下取
        getFloorTwo:function(valueF,valueS){ 
        	var $t=this;
        	return $t.accDiv(Math.floor($t.accMul($t.accMul(valueF,valueS),100)),100); 
        },
        //销毁模态
        destroyModal:function(ele){
        	$("#"+ele).modal("hide"); 
			$("#"+ele).empty();
			$("#"+ele).remove();
        },
		//返回筛选器对象,用于链式操作
    	hsOle: function() {
            return this.$element;      
        }, 
    }
})(jQuery);